<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" size="small"  type="primary" v-waves icon="el-icon-plus" @click="handleUpdate(null)">添加</el-button>

      <el-input @keyup.enter.native="handleFilter" size="small"  style="width: 200px;" class="filter-item" placeholder="商品名称" v-model="filters['like$goods.title']"></el-input>

      <el-select size="small" v-model="filters['goods.status']" clearable placeholder="商品状态">
        <el-option v-for="(item,index) in goodsStatusData()" :key="index" :label="item" :value="index">
        </el-option>
      </el-select>

      <category-cascader :clearable="true" v-model="filters['startWith$goods_category.path']"></category-cascader>

      <el-button class="filter-item" type="primary"  size="small" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="primary" size="small" v-waves icon="el-icon-document" @click="exportExcelFile">导出</el-button>
    </div>
    <el-table size="smamedium" :fit="true" :data="list" height="700" @sort-change="sortChange" v-loading="listLoading" element-loading-text="给我一点时间" border
      highlight-current-row style="width: 100%">
      <el-table-column align="center" type="index" label="序号" width="60" fixed="left">
      </el-table-column>
      <el-table-column prop="cover" align="center" label="封面" width="200" fixed="left">
        <template slot-scope="scope">
          <img :src="scope.row.cover|absUrl" alt="" class="avatar">
        </template>
      </el-table-column>
      <el-table-column prop="goodsNo" align="center" label="商品编号" fixed="left">
        <template slot-scope="scope">
          <span>{{scope.row.goodsNo}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="title" align="center" label="商品名称" width="160" fixed="left">
        <template slot-scope="scope">
          <span>{{scope.row.title}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="providerName" align="center" label="供应商" >
        <template slot-scope="scope">
          <span>{{scope.row.providerName||'中油BP'}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="goodsCategoryName" align="center" label="类别名称" >
        <template slot-scope="scope">
          <span>{{scope.row.goodsCategoryName}}</span>
        </template>
      </el-table-column>



      <el-table-column prop="marketPrice" align="center" label="市场价" >
        <template slot-scope="scope">
          <span>{{scope.row.marketPrice}}</span>
        </template>
      </el-table-column>


      <el-table-column prop="price" align="center" label="微信价" >
        <template slot-scope="scope">
          <span>{{scope.row.price}}</span>
        </template>
      </el-table-column>


      <el-table-column prop="points" align="center" label="积分价" >
        <template slot-scope="scope">
          <span>{{scope.row.points}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="tagIds" align="center" label="商品标签" >
        <template slot-scope="scope">
          <span>{{scope.row.tagName}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="brandId" align="center" label="品牌" >
        <template slot-scope="scope">
          <span>{{scope.row.brandName}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" label="商品状态" >
        <template slot-scope="scope">
          <el-tag :type="scope.row.status|tagStatus">{{scope.row.status|goodsStatus}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="status" align="center" label="审核状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.audit_step|tagStatus">{{scope.row.audit_step|authStatusFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" label="审核理由" width="120">
        <template slot-scope="scope">
          {{scope.row.approve_remark}}
        </template>
      </el-table-column>

      <el-table-column prop="stock" align="center" label="库存" sortable>
        <template slot-scope="scope">
          <span>{{scope.row.stock}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="stock" align="center" label="排序" sortable>
        <template slot-scope="scope">
          <span>{{scope.row.sort}}</span>
        </template>
      </el-table-column>

      <el-table-column align="left" label="操作" width="260">
        <template slot-scope="scope">

          <div class="btns">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="success" @click="showRuleDialog(scope.row)">规格</el-button>
            
            <el-button size="mini" v-if="userInfo.userType==0 && scope.row.audit_step!=2" type="default" @click="handleCommand(scope.row,'authPassed')">审核通过</el-button>
            <el-button size="mini" v-if="userInfo.userType==0 && scope.row.audit_step!=9" type="success" @click="handleCommand(scope.row,'unAuthPassed')">审核拒绝</el-button>
          </div>


        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="params.page"
        :page-sizes="[10,20,30,50]" :page-size="params.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="规格管理" :visible.sync="ruleDialogVisible" width="1200px">
      <el-form class="dialog-form" ref="ruleDialogForm" label-position="left" label-width="120px">
        <el-form-item label="商品规格" prop="goodsRule">
          <goosds-rule ref="goodsRule" :goodsRuleValues="temp.goodsRule" @hasNewGoodRules="hasNewGoodRules=true" @hasNoNewGoodRules="hasNewGoodRules=false"></goosds-rule>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="ruleDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitRuleFormAction">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible" width="1200px">
      <el-form class="dialog-form" :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px">

        <el-form-item label="商品名称" prop="title">
          <el-input v-model="temp.title" placeholder="商品名称"></el-input>
        </el-form-item>

        <el-form-item label="封面" prop="cover">
          <el-upload class="avatar-uploader" :action="UPLOAD_URL" :show-file-list="false" :on-success="handleAvatarSuccess('cover')"
            :before-upload="beforeAvatarUpload">
            <img v-if="temp.cover" :src="temp.cover|absUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品图片" prop="imgSrcs">
          <xd-upload v-model="temp.imgSrcs"></xd-upload>
        </el-form-item>


        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属分类" prop="categoryPath">
              <category-cascader placeholder="所属分类" v-model="temp.categoryPath"></category-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属品牌" prop="brandId">
              <xd-select v-model="temp.brandId" url="goods_brand"></xd-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品标签定义" prop="tagId">
          <el-radio-group v-model="temp.tagId">
            <el-radio :label="item.value" v-for="item in goodsTagItems" :key="item.value">{{item.text}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="!hasNewGoodRules">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="商品编号" prop="goodsNo">
                <el-input v-model="temp.goodsNo" placeholder="商品编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品库存" prop="stock">
                <el-input-number v-model="temp.stock" :min="0" placeholder="商品库存"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="警戒库存" prop="alertStock">
                <el-input-number v-model="temp.alertStock" :min="0" placeholder="警戒库存"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="市场价" prop="marketPrice">
                <el-input-number v-model="temp.marketPrice" :min="0" placeholder="市场价"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="微信价" prop="price">
                <el-input-number v-model="temp.price" :min="0" placeholder="微信价"></el-input-number>

              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="积分价" prop="points">
                <el-input-number v-model="temp.points" :min="0" placeholder="积分价"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </template>


        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售状态" prop="status">
              <el-radio-group v-model="temp.status">
                <el-radio :label="index" v-for="(item,index) in goodsStatusData()" :key="index">{{item}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐" prop="sort">
               <el-input-number v-model="temp.sort" placeholder="推荐"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品详情" prop="content">
          <div class="quill-wrap" style="height:500px;">
            <quill-editor style="height:400px;" v-model="temp.content" ref="myQuillEditor" :options="editorOption">
            </quill-editor>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitFormAction">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import categoryCascaderVue from "../../components/categoryCascader.vue";

import { quillEditor, Quill } from "vue-quill-editor";
import { container, ImageExtend, QuillWatch } from "quill-image-extend-module";
import xdUploadVue from "../../components/xdUpload.vue";
import goodsRuleVue from "../../components/goodsRule.vue";
import { getUserInfo } from '../../utils/auth';

Quill.register("modules/ImageExtend", ImageExtend);
let userInfo = getUserInfo();
console.log(userInfo);
export default {
  components: {
    "category-cascader": categoryCascaderVue,
    quillEditor,
    "goosds-rule": goodsRuleVue,
    "xd-upload": xdUploadVue
  },
  data() {
    return {
      userInfo,
      hasNewGoodRules: false,
      uillUpdateImg: false,
      isAddingRule: false,
      total: 0,
      goodsTagItems: [],
      editorOption: {
        placeholder: "在这里输入内容",
        modules: {
          ImageExtend: {
            loading: true,
            name: "file",
            action: this.UPLOAD_URL,
            response: res => {
              return res.info;
            }
          },
          toolbar: {
            container: container,
            handlers: {
              image: function() {
                QuillWatch.emit(this.quill.id);
              }
            }
          }
        }
      },
      temp: {
        id: "",
        imgSrcs: "",
        cover: "",

        categoryId: "",

        typeId: "",

        title: "",

        intro: "",
        categoryPath: "",
        shopNo: "",

        goodsUnit: "",

        tagIds: "",

        status: "",

        freightTemplateId: "",

        marketPrice: "",

        price: 0,
        sort: 0,
        points: "",
        goodsRule: "",
        goodsNo: "",

        stock: "",

        alertStock: "",

        content: "",

        brandId: ""
      },
      ruleDialogVisible: false,
      rules: {
        cover: [
          {
            required: true,
            message: "封面不能为空",
            trigger: "change"
          }
        ],
        categoryPath: [
          {
            required: true,
            message: "所属分类不能为空",
            trigger: "change"
          }
        ],

        imgSrcs: [
          {
            required: true,
            message: "请上传至少一张商品图片",
            trigger: "change"
          }
        ],

        title: [
          {
            required: true,
            message: "商品名称不能为空",
            trigger: "change"
          },
          {
            max: 60,
            message: "商品名称不能大于60个字",
            trigger: "change"
          }
        ],

        intro: [
          {
            required: true,
            message: "商品简介不能为空",
            trigger: "change",
            max: 900
          }
        ],

        shopNo: [
          {
            required: true,
            message: "商家编码不能为空",
            trigger: "change",
            max: 60
          }
        ],

        goodsUnit: [
          {
            required: true,
            message: "计量单位不能为空",
            trigger: "change",
            max: 60
          }
        ],

        status: [
          {
            required: true,
            message: "销售状态未指定",
            trigger: "change"
          }
        ],

        freightTemplateId: [
          {
            required: true,
            message: "运费模板不能为空",
            trigger: "change"
          }
        ],

        marketPrice: [
          {
            required: true,
            message: "市场价不能为空",
            trigger: "change"
          }
        ],

        price: [
          {
            required: true,
            message: "微信价不能为空",
            trigger: "change"
          }
        ],

        points: [
          {
            required: true,
            message: "积分价不能为空",
            trigger: "change"
          }
        ],

        goodsNo: [
          {
            required: true,
            message: "货号不能为空",
            trigger: "change",
            max: 60
          }
        ],

        stock: [
          {
            required: true,
            message: "商品库存不能为空",
            trigger: "change"
          }
        ],

        alertStock: [
          {
            required: true,
            message: "警戒库存不能为空",
            trigger: "change"
          }
        ],

        content: [
          {
            required: true,
            message: "商品详情不能为空",
            trigger: "change"
          }
        ],

        brandId: [
          {
            required: true,
            message: "请选择品牌",
            trigger: "change"
          }
        ]
      }
    };
  },

  created() {
    this.init("goods", 1).loadData();

    this.combOptions("goods_tag").then(info => {
      this.goodsTagItems = info;
    });
  },
  methods: {
    submitRuleFormAction() {
      if (this.submiting) {
        return;
      }
      let data = this.$refs["goodsRule"].getData();
      this.submiting = true;
      this.$post("/admin/goods/saveGoodsRule", {
        id: this.temp.id,
        goodsRule: JSON.stringify(data)
      })
        .then(_ => {
          this.ruleDialogVisible = false;
          this.$$notify("操作成功");
          this.submiting = false;
        })
        .catch(_ => {
          this.submiting = false;
        });
    },
    showRuleDialog(row) {
      this.temp.goodsRule = row.goodsRule;
      this.temp.id = row.id;
      this.ruleDialogVisible = true;
    },
    __onParseFilterValue(field, eq, value) {
      if (value) {
        if (field == "goods_category.path") {
          return "," + value.replace(/^,|,$/g, "") + ",";
        }
      }
      return value;
    },
    handleCommand(row, command) {
      let postData = (value, isPassed) => {
        this.$post("/admin/goods/" + command, {
          id: row.id,
          approve_remark: value
        }).then(res => {
          if (isPassed) {
            row.audit_step = 2;
          } else {
            row.audit_step = 9;
          }
          this.$$notify("操作成功");
        });
      };
      if (command == "unAuthPassed") {
        this.$prompt("请输入审核拒绝理由", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        })
          .then(({ value }) => {
            postData(value);
          })
          .catch(() => {});
      } else {
        this.$$comfirm("确定审核通过吗？", () => {
          postData("", 1);
        });
      }
    },
    exportExcelFile() {
      this.exportExcel({
        title: "商品",
        fields: [
          {
            field: "goodsNo",
            title: "商品编号"
          },

          {
            field: "title",
            title: "商品名称"
          },

          {
            field: "categoryName",
            title: "所属分类"
          },
          {
            field: "brandName",
            title: "商品品牌"
          },
          {
            field: "tagName",
            title: "标签"
          },
          {
            field: "status",
            title: "销售状态",
            valueMap: this.goodsStatusData()
          },
          {
            field: "marketPrice",
            title: "市场价"
          },
          {
            field: "price",
            title: "微信价"
          },
          {
            field: "points",
            title: "积分价"
          },
          {
            field: "stock",
            title: "商品库存"
          },
          {
            field: "alertStock",
            title: "警戒库存"
          },
          {
            field: "content",
            title: "商品详情"
          }
        ]
      }).then(info => {
        this.openWin(info);
      });
    }
  }
};
</script>
<style scoped>
.avatar {
  height: auto;
  display: block;
  margin: 0 auto;
  width: 100px;
}

.btns {
  padding-left: 15px;
}

.btns /deep/ button {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
